//@Login && Register
const express = require('express')
const router = express.Router()
const User = require('../../models/User')
const bcrypt = require('bcrypt')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require('../../config/keys')
const passport = require('passport')

// $route GET api/users/test
// @desc return req's JSON
// @access public
router.get("/test", (req,res) => {
  res.json({
    msg: "login words"
  })
})

// $route POST api/users/register
// @desc return req's JSON
// @access public
router.post("/register", (req,res) => {
  User.findOne({ email: req.body.email}).then((user) => {
    if(user) {
      return res.status(400).json({email: "邮箱已存在"})
    }else {
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar: gravatar.url(req.body.email,{s:'200',r:'pg',d:'mm'}),
        password: req.body.password,
        identity: req.body.identity
      })
      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, (err,hash) => {
          if(err) throw err
          newUser.password = hash
          newUser.save().then(user => res.json(user)).catch(err => console.log(err))
        })
      })
    }
  })
})

// $route POST api/users/login
// @desc return token use JWT passport
// @access public
router.post("/login", (req,res) => {
  const email = req.body.email
  const password = req.body.password
  //查询用户
  User.findOne({email}).then(user => {
    if(!user) {
      return res.status(404).json({email: "用户不存在!"})
    }
    //密码匹配
    bcrypt.compare(password, user.password).then(isMatch => {
      if(isMatch) {
        const rule = {id:user.id,name:user.name,avatar: user.avatar,identity: user.identity}
        jwt.sign(rule,keys.secretOrKey,{expiresIn: 720},(err, token)=>{
          if(err) throw err;
          res.json({
            success: true,
            token: "Bearer "+ token
          })
        })
      }else {
        return res.status(400).json({msg: "密码错误！"})
      }
    })
  })
})

// $route POST api/users/current
// @desc return current userInfo
// @access private
router.get("/current",passport.authenticate("jwt",{session: false}), (req,res) => {
  res.json({
    email: req.user.email,
    name: req.user.name,
    id: req.user.id,
    identity: req.user.identity
  })
})

module.exports = router